<script setup>
import {ref, onMounted, computed} from 'vue'
import { sessionApi, listTypeApi, treeTypeApi, sortTypeApi, saveTypeApi, delTypesApi, oneTypeApi } from '@/common/api'
import router from '@/common/router'
import Note from '@/components/notify'
import Msg from '@/components/message'
import Confirm from '@/components/confirm'
import { CScrollbar } from 'c-scrollbar'
import { formatDate } from '@/common/filter'
import UbtUpload from '@/components/upload/UbtUpload.vue'
import UbtTreeSel from '@/components/cascader/UbtTreeSel.vue'

// 自动加载，判断权限
onMounted(() => {
  checkAuth()
})

// 组织种类 1表示组织分类，2表示文件分类，3表示资讯分类，4表示视频资讯分类
const typeKind = 1

const procAuth = ref({
  addAuth: false,
  delAuth: false,
  edtAuth: false
})
// checkAuth 获取权限
const checkAuth = async () => {
  const res = await sessionApi()
  if (res.code === 200) {
    const userBtnCode = res.data.btnCodes
    procAuth.value = {
      addAuth: userBtnCode.indexOf('1001010401') !== -1,
      delAuth: userBtnCode.indexOf('1001010402') !== -1,
      edtAuth: userBtnCode.indexOf('1001010403') !== -1
    }
    list()
  } else {
    Msg({ kind: 'error', txt: res.msg })
    router.replace('/login')
  }
}

const schObj = {
  kind: typeKind
}
const schRef = ref(schObj)
const typeList = ref([])
const hasData = ref(false)
const checkList = ref([])
// list 列表展示
const list = async () => {
  hasData.value = false
  const res = await listTypeApi(schRef.value)
  if(res.code===200 && res.data && res.data.length>0) {
    hasData.value = true
    typeList.value = res.data
    idList.value = []
    checkList.value = []
    allCheck.value = false
    res.data.forEach(() => {
      checkList.value.push(false)
    })
  }
}

// 选择效果实现
const idList = ref([])
const allCheck = ref(false)
// checkAll 全选
const checkAll = () => {
  idList.value = []
  checkList.value = []
  allCheck.value = !allCheck.value
  if(allCheck.value) {
    typeList.value.forEach(item => {
      idList.value.push(item.typeId)
      checkList.value.push(true)
    })
  } else {
    typeList.value.forEach(() => {
      checkList.value.push(false)
    })
  }
}
// checkCurId 单选
const checkCurId = (idx, typeId) => {
  if(!checkList.value[idx]) {
    idList.value.push(typeId)
  } else {
    let index = idList.value.findIndex(id => {
      if(id === typeId){
        return true
      }
    })
    idList.value.splice(index, 1)
  }
  checkList.value[idx] = !checkList.value[idx]
}

const typeObj = {
  typeId: '',
  typeName: '',
  shortName: '',
  fullName: '',
  typeCode: '',
  logoId: '',
  logoName: '',
  logoUrl: '',
  kind: typeKind,
  parentId: '',
  parentName: '',
  parentCode: '',
  sort: 0,
  remarks: '',
}
const typeForm = ref(typeObj)
// add 新增
const showModal = ref(false)
const add = () => {
  showModal.value = true
  getTypeTree()
}
// update 修改
const imgRef = ref()
const update = async (typeId) => {
  const res = await oneTypeApi({typeId})
  if(res.code === 200) {
    typeForm.value = res.data
    if(typeForm.value.logoId && typeForm.value.logoId!=='') {
      imgRef.value = {id: typeForm.value.logoId, name: typeForm.value.logoName, url: typeForm.value.logoUrl, thumb: typeForm.value.logoUrl.replace('/img', '/img/thumb')}
    }
    getTypeTree()
    showModal.value = true
  } else {
    Msg({ kind: 'info', txt: '暂无内容' })
  }
}
// save 保存提交
const save = async () => {
  let typeId = typeForm.value.typeId
  let typeName = typeForm.value.typeName
  let typeCode = typeForm.value.typeCode
  let parentId = typeForm.value.parentId
  let sort = parseInt(typeForm.value.sort)
  typeForm.value.sort = sort
  if(typeName === '' || typeName.length > 85) {
    Msg({ kind: 'warn', txt: '组织的名称不能为空，且长度不超过50个字符' })
    return
  } else if(typeCode === '' || typeCode.length > 85) {
    Msg({ kind: 'warn', txt: '组织的编码不能为空' })
    return
  } else if(parentId === '' || parentId.length !== 21) {
    Msg({ kind: 'warn', txt: '父级组织不能为空' })
    return
  } else if(sort < 1) {
    Msg({ kind: 'warn', txt: '组织排序不能为空' })
    return
  } else if(typeId === parentId) {
    Msg({ kind: 'warn', txt: '不可选择当前组织为父级组织' })
    return
  }
  if(imgRef.value && imgRef.value.id) {
    typeForm.value.logoId = imgRef.value.id
    typeForm.value.logoName = imgRef.value.name
    typeForm.value.logoUrl = imgRef.value.url
  }
  const res = await saveTypeApi(typeForm.value)
  if(res.code === 200) {
    closeModal()
    list()
    Note({ kind: 'success', title: '成功', txt: '恭喜您，组织信息保存成功！' })
  } else {
    Msg({ kind: 'error', txt: res.msg })
  }
}

// closeModal 关闭弹出层，并重置表单数据
const closeModal = () => {
  showModal.value = false
  typeForm.value = {
    typeId: '',
    typeName: '',
    shortName: '',
    fullName: '',
    typeCode: '',
    logoId: '',
    logoName: '',
    logoUrl: '',
    kind: typeKind,
    parentId: '',
    parentName: '',
    parentCode: '',
    sort: 0,
    remarks: '',
  }
  imgRef.value = null
}

// deletes 删除组织
const deletes = async() => {
  if(!idList || idList.value.length===0) {
    Msg({ kind: 'warn', txt: '请至少选择一项再操作！' })
    return
  }
  Confirm('删除组织，会将其子组织一起删除，确定这样操作吗？').then(() => {
    delTypes()
  }).catch(() => {
    Msg({ kind: 'info', txt: "取消处理选中的数据！" })
  })
}
// delTypes 删除组织实现，分离出来防止调用时异步报错
const delTypes = async () => {
  let typeIds = idList.value.join(',')
  const res = await delTypesApi({ typeIds, kind: typeKind })
  if(res.code === 200) {
    list()
    Note({ kind: 'success', title: '成功', txt: '恭喜您，组织信息删除成功！' })
  } else {
    Msg({ kind: 'error', txt: res.msg })
  }
}

// 获取组织树
const treeRef = ref([])
const getTypeTree = async () => {
  const res = await treeTypeApi({kind: typeKind})
  if(res.code === 200) {
    treeRef.value = res.data
  }
  if(!res.data) {
    treeRef.value = []
  }
  treeRef.value.unshift({
    selId: '111111111111111111111',
    selName: '一级组织',
    selCode: '1000',
    selPid: '000000000000000000000',
    chked: false,
    children: null
  })
}

const setValue = (type) => {
  sortType(type.selId)
  typeForm.value.parentId = type.selId
  typeForm.value.parentName = type.selName
  typeForm.value.parentCode = type.selCode
}

// sortType 组织排序
const sortType = async (parentId) => {
  const res = await sortTypeApi({ parentId, kind: typeKind })
  if(res.code === 200) {
    typeForm.value.sort = res.data
  }
}

// fmtDate 时间戳转时间
const fmtDate = computed(() => {
  return (time, kind) => {
    let date = new Date(time*1000)
    return formatDate(date, kind)
  }
})

// setUrl 回调获取上传文件的地址
const setUrl = (kind, types, file) => {
  typeForm.value.logoId = file.id
  typeForm.value.logoName = file.name
  typeForm.value.logoUrl = file.url
}
</script>

<template>
  <div class="a">
    <!-- 头部按钮 -->
    <div class="b">
      <div v-if="procAuth.addAuth" class="btn-p" title="新增" @click="add()"><i class="iconfont doc_text"></i> 新增</div>
      <div v-if="procAuth.delAuth" class="btn-d" title="删除" @click="deletes()"><i class="iconfont trash"></i> 删除</div>
      <div class="btn-r" title="刷新" @click="list()"><i class="iconfont arrow__circlepath"></i></div>
    </div>
    <!-- 中部数据 -->
    <div class="c" v-if="hasData">
      <table>
        <tr>
          <th style="width: 5%;"><i @click="checkAll()" :class="['iconfont', allCheck ? 'checkmark_square_fill chked' : 'app chk']"></i></th>
          <th style="width: 25%;">名称</th>
          <th style="width: 20%;">简称</th>
          <th style="width: 10%;">编码</th>
          <th style="width: 10%;">排序</th>
          <th style="width: 20%;">时间</th>
          <th style="width: 10%;">操作</th>
        </tr>
        <tr v-for="(curType, index) in typeList" :key="curType.typeId" class="tr-style">
          <td class="txt-center"><i @click="checkCurId(index, curType.typeId)" :class="['iconfont', checkList[index] ? 'checkmark_square_fill chked' : 'app chk']"></i></td>
          <td><div :style="{'padding-left': curType.typeLevel*15+'px'}">{{curType.typeName}}</div></td>
          <td class="txt-center">{{curType.shortName}}</td>
          <td class="txt-center">{{curType.typeCode}}</td>
          <td class="txt-center">{{curType.sort}}</td>
          <td class="txt-center">{{fmtDate(curType.addTime, 2)}}</td>
          <td class="txt-center">
            <span v-if="procAuth.edtAuth" class="cl-blue" title="修改" @click="update(curType.typeId)"><i class="iconfont square_pencil"></i> 修 改</span>
          </td>
        </tr>
      </table>
    </div>
    <div v-else class="no-data">暂无内容</div>

    <!-- 新增、修改弹出层 -->
    <transition name="fade-mod" appear>
      <div v-if="showModal" class="modal-backdrop">
        <c-scrollbar>
          <div class="modal" style="width: 600px;">
            <div class="modal-header">
              <div class="header-left"><i class="iconfont doc_plaintext fs20"></i> 保存组织信息</div>
              <div class="header-right" @click="closeModal()"><i class="iconfont xmark fs20"></i></div>
            </div>
            <div class="modal-body">
              <div>
                <div class="ipt-title"><span class="required">*</span>父级组织</div>
                <ubt-tree-sel :tree-list="treeRef" :kind="1" :inboxed="false" :curName="typeForm.parentName ? typeForm.parentName+'['+typeForm.parentCode+']' : ''" pre-name="父级组织" @setValue="setValue" />
              </div>
              <div>
                <div class="ipt-title"><span class="required">*</span>组织排序</div>
                <div><input type="text" v-model="typeForm.sort" maxlength="11" placeholder="请输入组织排序" class="txt" /></div>
              </div>
              <div>
                <div class="ipt-title"><span class="required">*</span>组织名称</div>
                <div><input type="text" v-model="typeForm.typeName" maxlength="85" placeholder="请输入组织名称" class="txt" /></div>
              </div>
              <div>
                <div class="ipt-title"><span class="required">*</span>组织编码</div>
                <div><input type="text" v-model="typeForm.typeCode" maxlength="50" placeholder="请输入组织编码" class="txt" /></div>
              </div>
              <div>
                <div class="ipt-title"><span class="required"></span>组织全称</div>
                <div><input type="text" v-model="typeForm.fullName" maxlength="85" placeholder="请输入组织全称" class="txt" /></div>
              </div>
              <div>
                <div class="ipt-title"><span class="required"></span>组织简称</div>
                <div><input type="text" v-model="typeForm.shortName" maxlength="85" placeholder="请输入组织简称" class="txt" /></div>
              </div>
              <div>
                <div class="ipt-title"><span class="required"></span>组织图标</div>
                <div><UbtUpload :kind="1" :types="1" :file="imgRef" @setUrl="setUrl"></UbtUpload></div>
              </div>
            </div>
            <div class="modal-footer">
              <div class="btn-p" @click="save"><i class="iconfont today_fill"></i> 保存</div>
              <div class="btn-d" @click="closeModal"><i class="iconfont arrowshape_turn_up_left"></i> 取消</div>
            </div>
          </div>
        </c-scrollbar>
      </div>
    </transition>
  </div>
</template>

<style scoped>
.a {width: 100%; height: 100%;}
.b {padding: 10px 20px; display: flex; display: -webkit-flex;}
.c {background-color: #FFF;}
</style>
